<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2018/11/5
 * Time: 16:11
 */

namespace Xiaoqu\Controller;
use Common\Controller\HomebaseController;

class XqAdvertisingController extends HomebaseController {
    protected $page_size;
    public $district;
    public $advertising;
    public $category;
    public $price;
    public $year;
    function _initialize() {
        parent::_initialize();
        $this->page_size    = 20;
        $this->district     = ['东城区', '西城区', '朝阳区', '丰台区', '海淀区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区', '石景山区', '门头沟区'];
        $this->advertising  = ['电梯电视屏', '道闸', '快递柜箱体', '水机箱体', '人行门'];
        $this->category     = ['商住楼' => 3, '综合体' => 4, '写字楼' => 2, '中高端住宅' => 1];
        $this->price        = [10000, 20000, 40000, 60000, 80000, 100000, 999999999];
        $this->year         = ['2000 年以前', '2000-2005年', '2005-2010年', '2010-2015年', '2010-2019年'];
    }

    public function search()
    {
        $lng            = I('get.lng', 0);                  // 经度
        $lat            = I('get.lat', 0);                  // 纬度
        $location       = I('get.location', "");            // 搜索地点
        $distance       = I('get.distance', 10000);         // 距离
        $category       = I('get.category', 0);             // 住宅类型
        $district       = I('get.district', 0);             // 行政区域
        $advertising    = I('get.advertising', 0);          // 广告类型
        $price          = I('get.price', 0);                // 价格区间
        $year           = I('get.year', 0);                 // 建筑年代
        $p              = I('get.p', 0);                    // 分页

        if (($lng && $lat) || $district > 0 || $location) {
            if ($location) {
                if (strpos($location, "区")) {
                    if (preg_match("/(.*?(市))?(.*?(区))(.*)/", $location, $match)) {
                        $location   = "北京市" . $match[3] . $match[5];
                        $url        = "http://api.map.baidu.com/geocoding/v3/?address=$location&output=json&ak=p1dVi5KCcYv1HEgLMtfLcHuNu0TRR97g";
                        $re         = curl_requestion($url);
                        $loc_info   = json_decode($re['data'], true);
                        if ($loc_info['status'] == 0) {
                            $lng    = $loc_info['result']['location']['lng'];
                            $lat    = $loc_info['result']['location']['lat'];
                        } else {
                            $this->ajaxReturn(['msg' => "获取地址信息失败"]);exit();
                        }
                    }
                } else {
                    $this->ajaxReturn(['msg' => "请输入行政区名称"]);exit();
                }
            }

            $where  = array();
            $model  = M('xq_advertising');
            $lists  = [];
            $info   = [];

            if ($category) {
                // 住宅类型
                $where['xq_type'] = $category;
            }
            if ($price) {
                // 价格检索
//                $min = $this->price[$price - 1];
//                $max = $this->price[$price];
//                $where[] = " ((min_price >= $min and min_price <= $max) OR (max_price >= $min and max_price <= $max)) ";

                $where['min_price'] = ["EGT", $this->price[$price - 1]];
                $where['max_price'] = ["ELT", $this->price[$price]];
            }
            if ($year) {
                switch ($year) {
                    case 1 :
                        $where['Year(build_time)'] = ['ELT', 2000];
                        break;
                    case 2 :
                        $where['Year(build_time)'] = ['EGT', 2000];
                        $where['Year(build_time)'] = ['ELT', 2005];
                        break;
                    case 3 :
                        $where['Year(build_time)'] = ['EGT', 2005];
                        $where['Year(build_time)'] = ['ELT', 2010];
                        break;
                    case 4 :
                        $where['Year(build_time)'] = ['EGT', 2010];
                        $where['Year(build_time)'] = ['ELT', 2015];
                        break;
                    default:
                        $where['Year(build_time)'] = ['GT', 2015];
                }
            }

            if ($district > 0) {
                // 行政区域
                $where['xq_district'] = $this->district[$district - 1];
                // 统计
                $info = $model
                    ->field("count(*) as count, sum(xinchao_elevator) as xinchao_elevator_count")
                    ->where($where)
                    ->find();
                // 列表
                $lists  = $model
                    ->where($where)
                    ->order("id asc")
                    ->limit($p * $this->page_size, $this->page_size)
                    ->select();

            } elseif($lng && $lat) {
                $where['lng'] = ['GT', $lng - $distance];
                $where['lng'] = ['LT', $lng + $distance];
                $where['lat'] = ['GT', $lat - $distance];
                $where['lat'] = ['LT', $lat + $distance];

                $temp       = "ROUND( 6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat * PI() / 180 - lat * PI() / 180) / 2), 2) + COS($lat * PI() / 180) * COS( lat * PI() / 180) * POW(SIN(( $lng * PI() /180 - lng * PI() / 180) / 2), 2))) * 1000) AS distance";
                $sub_sql    = $model
                    ->field("id, xinchao_elevator, $temp")
                    ->having("distance < $distance * 1000")
                    ->where($where)
                    ->buildSql();
                $sql    = "SELECT count(*) as count,sum(xinchao_elevator) as xinchao_elevator_count FROM " . $sub_sql . " temp limit 1";
                $info   = $model->query($sql)[0];

                // 列表
                $field = "*, $temp";
                $lists  = $model
                    ->field($field)
                    ->where($where)
                    ->having("distance < $distance * 1000")
                    ->order("distance asc")
                    ->limit($p * $this->page_size, $this->page_size)
                    ->select();
            }

            // 计算距离
            foreach ($lists as &$v) {
                $v['distance'] = $this->get_distance($lat, $lng, $v['lat'], $v['lng']);
                $v['build_time_desc'] = substr($v['build_time_desc'], 0, 4);
            }
            $this->ajaxReturn(['status' => 1, 'lists' => $lists, 'count' => $info['count'], 'xinchao_elevator_count' => $info['xinchao_elevator_count']]);
        } else {
            $this->ajaxReturn(['msg' => '未获取到位置信息']);
        }
    }

    public function get_distance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000; //地球半径m

        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;

        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        $calcLongitude  = $lng2 - $lng1;
        $calcLatitude   = $lat2 - $lat1;
        $stepOne        = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo        = 2 * asin(min(1, sqrt($stepOne)));

        return round($earthRadius * $stepTwo / 1000);
    }
}
